package com.example.myweather;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myweather.db.City;
import com.example.myweather.db.County;
import com.example.myweather.db.Province;
import com.example.myweather.util.HttpUtil;
import com.example.myweather.util.Utility;

import org.jetbrains.annotations.NotNull;
import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ChooseAreaFragment extends Fragment {


    private static final int LEVEL_PROVINCE = 0;
    private static final int LEVEL_CITY = 1;
    private static final int LEVEL_COUNTY = 2;

    private ProgressDialog progressDialog;//对话，考察的是UI设计
    private TextView titleview;
    private Button backButton;
    //列表前端设计
    private ListView listView;//考察的点就多了，使用ListView的方法和过程
    private ArrayAdapter<String> adapter;
    private List<String> dataList = new ArrayList<>();

    //下面主要就是对于本功能特殊的一些对象世界
    //省市县列表
    private List<Province> provinceList;
    private List<City> cityList;
    private List<County> countyList;
    //选择中的省市
    private Province selectedProvince;
    private City selectedCity;
    //选中的级别
    private int currentLevel;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public ChooseAreaFragment() {
        // Required empty public constructor
    }


    //视图
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_choose_area,container,false);
        titleview = view.findViewById(R.id.title_text);
        backButton = view.findViewById(R.id.back_button);
        listView = view.findViewById(R.id.list_view);
        adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1,dataList);//列表view中最关键的一部分
        listView.setAdapter(adapter);
        return view;
    }
    //在活动创建好后--需要回顾到fragment的生命周期
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //这个也是listView的基本操作
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(currentLevel == LEVEL_PROVINCE) {
                    //在选择省级这里
                    selectedProvince = provinceList.get(position);
                    queryCities();//查询城市
                }else if(currentLevel == LEVEL_CITY){
                    //重复性工作
                    selectedCity = cityList.get(position);
                    queryCounties();//查询县级城市
                }else if(currentLevel == LEVEL_COUNTY){
                    //weatherId 作为数据进行传递
                    String weatherId = countyList.get(position).getWeatherId();//得到点击的县的天气id
                    if(getActivity() instanceof  MainActivity){
                        //页面跳转
                        Intent intent = new Intent(getActivity(),WeatherActivity.class);
                        intent.putExtra("weather_id",weatherId);
                        startActivity(intent);
                        getActivity().finish();//这个页面关闭掉，不要浪费资源
                    }else if(getActivity() instanceof  WeatherActivity){
                        //直接在weatherActivity中重新刷新！
                        WeatherActivity weatherActivity = (WeatherActivity) getActivity();
                        weatherActivity.drawerLayout.closeDrawers();
                        weatherActivity.swipeRefreshLayout.setRefreshing(true);
                        weatherActivity.requestWeather(weatherId);
                    }

                }
            }
        });
        //设计好返回的back——button的作用
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(currentLevel == LEVEL_COUNTY){
                    queryCities();
                }else if(currentLevel == LEVEL_CITY){
                    queryProvinces();
                }
            }
        });
        queryProvinces();
    }

    //查询省市县的流程基本上就是一个套路来的主要是一些细节的不同，首先都是先去数据库查，若是没有就再去网络获取
    private void queryProvinces() {
        titleview.setText("中国");
        backButton.setVisibility(View.GONE);
        //这里用到数据库的litepal的方法
        provinceList = DataSupport.findAll(Province.class);
        if(provinceList.size() > 0){
            //更换list中的数据
            dataList.clear();
            for(Province province : provinceList){
                dataList.add(province.getProvinceName());
            }
            //更新细节
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = LEVEL_PROVINCE;
        }else {
            //没有的话那就先去网络获取数据
            String address ="http://guolin.tech/api/china";
            queryFormServer(address,"province");
        }
    }


    private void queryCities() {
        titleview.setText(selectedProvince.getProvinceName());
        backButton.setVisibility(View.VISIBLE);
        //这里用到数据库的litepal的方法
        cityList = DataSupport.where("provinceId = ?",String.valueOf(selectedProvince.getId())).find(City.class);
        if(cityList.size() > 0){
            //更换list中的数据
            dataList.clear();
            for(City city : cityList){
                dataList.add(city.getCityName());
            }
            //更新细节
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = LEVEL_CITY;
        }else {
            int provinceCode = selectedProvince.getProvinceCode();
            //没有的话那就先去网络获取数据
            String address ="http://guolin.tech/api/china/"+provinceCode;
            queryFormServer(address,"city");
        }
    }


    private void queryCounties() {
        titleview.setText(selectedCity.getCityName());
        backButton.setVisibility(View.VISIBLE);
        //这里用到数据库的litepal的方法
        countyList = DataSupport.where("cityId = ?",String.valueOf(selectedCity.getId())).find(County.class);
        if(countyList.size() > 0){
            //更换list中的数据
            dataList.clear();
            for(County county : countyList){
                dataList.add(county.getCountyName());
            }
            //更新细节
            adapter.notifyDataSetChanged();
            listView.setSelection(0);
            currentLevel = LEVEL_COUNTY;
        }else {
            int provinceCode = selectedProvince.getProvinceCode();
            int cityCode = selectedCity.getCityCode();
            //没有的话那就先去网络获取数据
            String address ="http://guolin.tech/api/china/"+provinceCode+"/"+cityCode;
            queryFormServer(address,"county");
        }
    }
    //根据传入的地址和类型从服务器上查询省市县的数据
    private void queryFormServer(String address, String type) {
        showProgressDialog();
        HttpUtil.sendOkHttpRequest(address, new Callback() {
            //实现这个回传数据的方法
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();
                            Toast.makeText(getContext(),"加载失败",Toast.LENGTH_LONG).show();
                        }
                    });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                Log.d("Response", "onResponse: "+response.body().toString());
                String responseText = response.body().string();
                boolean result = false;
                if("province".equals(type)){
                    result = Utility.handleProvinceResponse(responseText);
                }else if("city".equals(type)){
                    result = Utility.handleCityResponse(responseText,selectedProvince.getId());
                }else if("county".equals(type)){
                    result = Utility.handleCountyResponse(responseText,selectedCity.getId());
                }
                if(result){
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            closeProgressDialog();
                            //再从数据库中读取
                            if ("province".equals(type)) {
                                queryProvinces();
                            } else if ("city".equals(type)) {
                                queryCities();
                            } else if ("county".equals(type)) {
                                queryCounties();
                            }
                        }
                    });
                }
            }
        });
    }

    private void closeProgressDialog() {
        if(progressDialog != null){
            progressDialog.dismiss();//关闭
        }
    }

    private void showProgressDialog() {
        if(progressDialog == null){
            //创建一个对象
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("加载中");
            progressDialog.setCanceledOnTouchOutside(false);
        }
        progressDialog.show();
    }

    //关闭
}